package slh.comment;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/comment")
public class commentServlet extends HttpServlet {
    private commentDao commentDao;

    @Override
    public void init() throws ServletException {
        super.init();
        commentDao = new commentDao();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            if ("getComments".equals(action)) {
                int contentId = Integer.parseInt(request.getParameter("contentId"));
                String contentType = request.getParameter("contentType");

                List<comment> comments = commentDao.getContentComments(contentId, contentType);
                double averageRating = commentDao.getAverageRating(contentId, contentType);
                int[] ratingCounts = commentDao.getRatingDistribution(contentId, contentType);

                request.setAttribute("comments", comments);
                request.setAttribute("avgRating", averageRating);
                request.setAttribute("ratingCounts", ratingCounts);

                request.getRequestDispatcher("/movieDetail.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "参数错误");
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        try {
            String action = request.getParameter("action");
            if (action == null) {
                out.write("{\"error\":\"缺少action参数\"}");
                return;
            }

            HttpSession session = request.getSession();
            String userId = (String) session.getAttribute("userId");
            if (userId == null) {
                out.write("{\"error\":\"请先登录\",\"redirect\":\"http://localhost:8081/#/\"}");
                return;
            }

            if ("addComment".equals(action)) {
                // 验证参数
                int contentId;
                try {
                    contentId = Integer.parseInt(request.getParameter("contentId"));
                } catch (NumberFormatException e) {
                    out.write("{\"error\":\"无效的contentId\"}");
                    return;
                }

                String contentType = request.getParameter("contentType");
                if (contentType == null || contentType.isEmpty()) {
                    out.write("{\"error\":\"缺少contentType参数\"}");
                    return;
                }

                int rating;
                try {
                    rating = Integer.parseInt(request.getParameter("rating"));
                    if (rating < 1 || rating > 5) {
                        out.write("{\"error\":\"评分必须在1-5之间\"}");
                        return;
                    }
                } catch (NumberFormatException e) {
                    out.write("{\"error\":\"无效的评分\"}");
                    return;
                }

                String commentText = request.getParameter("comment");
                if (commentText == null || commentText.trim().isEmpty()) {
                    out.write("{\"error\":\"评论内容不能为空\"}");
                    return;
                }

                // 检查是否已评论
                comment existingComment = commentDao.getUserContentComment(userId, contentId, contentType);
                if (existingComment != null) {
                    out.write("{\"error\":\"您已经评论过此内容\"}");
                    return;
                }

                // 添加新评论
                comment newComment = new comment();
                newComment.setUserId(userId);
                newComment.setContentId(contentId);
                newComment.setContentType(contentType);
                newComment.setRating(rating);
                newComment.setCommentText(commentText);

                boolean success = commentDao.addComment(newComment);

                if (success && "movie".equals(contentType)) {
                    commentDao.updateMovieRating(contentId);
                }
                if (success && "book".equals(contentType)) {
                    commentDao.updateBookRating(contentId);
                }

                out.write("{\"success\":true,\"message\":\"评论成功\"}");
            } else {
                out.write("{\"error\":\"不支持的操作\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.write("{\"error\":\"数据库错误: "+e.getMessage()+"\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.write("{\"error\":\"服务器错误: "+e.getMessage()+"\"}");
        } finally {
            out.close();
        }
    }
}